package com.example.votingsystem.service;

import com.example.votingsystem.entity.News;
import com.example.votingsystem.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class NewsService {

    @Autowired
    private NewsRepository newsRepository;

    public List<News> getAllActiveNews() {
        return newsRepository.findByIsActiveTrueOrderByCreatedAtDesc();
    }

    public List<News> getNewsByCategory(String category) {
        return newsRepository.findByIsActiveTrueAndCategoryOrderByCreatedAtDesc(category);
    }

    public News getNewsById(Long id) {
        return newsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("News not found"));
    }

    public News createNews(News news) {
        return newsRepository.save(news);
    }

    public News updateNews(News news) {
        if (!newsRepository.existsById(news.getId())) {
            throw new RuntimeException("News not found");
        }
        return newsRepository.save(news);
    }
}
